package com.wjw.utils;

import java.io.IOException;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 创建人:ZSF
 * 创建日期:2014年1月17日
 * 创建时间:下午11:52:34
 * 说      明:命令行工具类
 */
public final class CMDUtil {
	
    /**
     * 日志对象
     */
    protected static Logger log = LoggerFactory.getLogger(CMDUtil.class);
	
	/**
	 * 执行cmd命令，成功后返回true,失败后返回false
	 * @param cmd
	 * @return
	 */
	public static synchronized boolean executeCmdFlash(String cmd) {
		try {
			final Process process = Runtime.getRuntime().exec(cmd);
			Runtime.getRuntime().addShutdownHook(new Thread() {
				public void run() {
					process.destroy();
				}
			});
			StringBuffer stdout = new StringBuffer();
			InputStreamReader inputstreamreader = new InputStreamReader(
					process.getInputStream());
			char c = (char) inputstreamreader.read();
			if (c != '\uFFFF')
				stdout.append(c);
			while (c != '\uFFFF') {
				if (!inputstreamreader.ready()) {
					try {
						process.exitValue();
						break;
					} catch (IllegalThreadStateException _ex) {
						try {
							Thread.sleep(100L);
						} catch (InterruptedException _ex2) {
						}
					}
				} else {
					c = (char) inputstreamreader.read();
					stdout.append(c);
				}
			}
			try {
				inputstreamreader.close();
			} catch (IOException ioexception2) {
				log.error("RunCmd : Error closing InputStream " + ioexception2);
				return false;
			}
		} catch (Throwable e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
